import {create} from "zustand";
import {
    ChatSession,
    ChatSessionCreate,
    ChatSessionUpdate,
} from "@/types/chat-session";
import {
    clearSession,
    deleteChatSession,
    insertChatSession,
    selectChatSessionList,
    updateChatSession,
} from "@/services/sqlite/chat-session";
import loading from "@/components/Global/Loading";

interface ChatSessionState {
    state: {
        sessions: ChatSession[];
        totalUnreadCount: number; // 总未读消息数
        loading: boolean; // 是否正在加载会话列表
    };
    actions: {
        /**
         * 设置加载状态
         * @param loading 是否正在加载
         */
        setLoading: (loading: boolean) => void;
        /**
         * 获取整个会话列表
         */
        setSessions: (sessions: ChatSession[]) => void;
        /**
         * 添加一条会话记录
         * @param session
         */
        addSession: (session: ChatSession) => void;
        /**
         * 删除指定的会话记录
         * @param sessionId 会话ID
         */
        deleteSession: (sessionId: string) => void;
        /**
         * 批量删除会话记录
         * @param sessionIds 会话ID列表
         */
        deleteBatchSessions: (sessionIds: string[]) => void;
        /**
         * 更新指定会话的未读消息数
         * @param sessionId 会话ID
         * @param count 未读消息数
         */
        updateSession: (session: Omit<ChatSessionUpdate, "ownerId">) => void;
    };
}

const ChatSessionStateStore = create<ChatSessionState>((set, get) => ({
    state: {
        sessions: [],
        totalUnreadCount: 0, // 初始总未读消息数为0
        loading: false, // 初始状态为未加载
    },
    actions: {
        setLoading(loading: boolean): void {
            set((currentState) => ({
                state: {
                    ...currentState.state,
                    loading, // 设置加载状态
                },
            }));
        },
        setSessions(sessions: ChatSession[]): void {
            const count = sessions.map(session => session.unreadCount || 0).reduce((a, b) => a + b, 0)
            set((currentState) => ({
                state: {
                    ...currentState.state,
                    sessions, // 设置会话记录
                    totalUnreadCount: count, // 计算总未读消息数
                },
            }));
        },
        addSession: (session: ChatSession) => {
            set((currentState) => ({
                state: {
                    ...currentState.state,
                    sessions: [...currentState.state.sessions, session],
                    totalUnreadCount: currentState.state.totalUnreadCount + (session.unreadCount || 0), // 更新总未读消息数
                },
            }));
        },
        deleteSession: async (sessionId: string) => {
            // 从当前状态中移除
            set((currentState) => ({
                state: {
                    ...currentState.state,
                    sessions: currentState.state.sessions.filter(
                        (session) => session.sessionId !== sessionId
                    ),
                    totalUnreadCount: currentState.state.totalUnreadCount - (currentState.state.sessions.find(session => session.sessionId === sessionId)?.unreadCount || 0), // 更新总未读消息数
                },
            }));
        },
        deleteBatchSessions(sessionIds: string[]): void {
            // 批量删除会话记录
            set((currentState) => ({
                state: {
                    ...currentState.state,
                    sessions: currentState.state.sessions.filter(
                        (session) => !sessionIds.includes(session.sessionId)
                    ),
                    totalUnreadCount: currentState.state.totalUnreadCount - sessionIds.reduce((total, sessionId) => {
                        const session = currentState.state.sessions.find(s => s.sessionId === sessionId);
                        return total + (session?.unreadCount || 0);
                    }, 0), // 更新总未读消息数
                },
            }));
        },
        updateSession: (session: Omit<ChatSessionUpdate, "ownerId">) => {
            // 更新当前状态中的会话记录
            set((currentState) => ({
                state: {
                    ...currentState.state,
                    sessions: currentState.state.sessions.map((s) => {
                        if (s.sessionId === session.sessionId) {
                            return {
                                ...s,
                                ...session,
                            };
                        }
                        return s;
                    }),
                    // 更新总未读消息数
                    totalUnreadCount: currentState.state.totalUnreadCount + (session.unreadCount || 0) - (currentState.state.sessions.find(s => s.sessionId === session.sessionId)?.unreadCount || 0),
                },
            }));
        }
    },
}));

export default ChatSessionStateStore;
